package org.fickler

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{SaveMode, SparkSession}
import org.apache.spark.sql.functions.{col, count, substring, sum, to_date, year}

/**
 * @author Fickler
 * @date 2024/1/7 16:48
 */
object UkTime {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]").setAppName("UK")
    val sc = new SparkContext(conf)

    val spark = SparkSession.builder.appName("UkTime").getOrCreate()

    val accidents = spark.read.format("csv").option("header", "true").load("src\\main\\java\\org\\datas\\dft-road-casualty-statistics-accident-1979-2020.csv")

    val result = accidents
      .groupBy("accident_year")
      .agg(count("*").alias("accident_sum")).orderBy("accident_year")

    result.show()

    val outputPath = "src/main/java/org/UkResult/UkTime"
    result
      .coalesce(1)
      .write
      .mode("overwrite")
      .option("header", "true")
      .csv(outputPath)

    val mysqlUrl = "jdbc:mysql://localhost:3306/ukaccident"
    val mysqlProperties = new java.util.Properties()
    mysqlProperties.setProperty("user", "root")
    mysqlProperties.setProperty("password", "011216")
    mysqlProperties.setProperty("driver", "com.mysql.jdbc.Driver")

    result.write
      .mode(SaveMode.Overwrite)
      .jdbc(mysqlUrl, "UkTime", mysqlProperties)

    spark.stop()
  }

}
